package com.jyx.file_system.service;

import com.alibaba.fastjson.JSON;
import com.jyx.file_system.dao.FileSystemRepository;
import com.jyx.framework.domain.filesystem.FileSystem;
import com.jyx.framework.domain.filesystem.response.FileSystemCode;
import com.jyx.framework.domain.filesystem.response.UploadFileResult;
import com.jyx.framework.exception.ExceptionCast;
import com.jyx.framework.model.response.CommonCode;
import jdk.nashorn.internal.parser.JSONParser;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

@Service
public class FileSystemService {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemService.class);
    @Value("${jieyouxiang.fastdfs.tracker_servers}")
    String tracker_server;
    @Value("${jieyouxiang.fastdfs.connect_timeout_in_seconds}")
    int connect_timeout_in_seconds;
    @Value("${jieyouxiang.fastdfs.network_timeout_in_seconds}")
    int network_timeout_in_seconds;
    @Value("${jieyouxiang.fastdfs.charset}")
    String charset;

    @Autowired
    FileSystemRepository fileSystemRepository;

    /**
     * 初始化fdfs
     */
    public void initFdfsConfig(){
        try{
            /*ClientGlobal.initByTrackers(tracker_server);
            ClientGlobal.setG_connect_timeout(connect_timeout_in_seconds);
            ClientGlobal.setG_network_timeout(network_timeout_in_seconds);
            ClientGlobal.setG_charset(charset);*/
            ClientGlobal.initByProperties("config/fastdfs-client.properties");
            System.out.println("network_timeout = "+ClientGlobal.getG_network_timeout()+"ms");
            System.out.println("charset="+ClientGlobal.g_charset);
        }catch (Exception e){
            e.printStackTrace();
            ExceptionCast.cast(FileSystemCode.FILESYSTE_INITEROOR);
        }
    }

    /**
     * 文件上传业务方法
     * @param file
     * @param fileTag
     * @param businessKey
     * @param metadata
     * @return
     */
    public UploadFileResult upload(MultipartFile file,String fileTag,String businessKey,String metadata){
        if(file==null){
            ExceptionCast.cast(FileSystemCode.FILESYSTEM_FILEISNULL);
        }
        String fileId = fdfs_upload(file);
        FileSystem fileSystem = new FileSystem();
        fileSystem.setFileId(fileId);
        fileSystem.setFileName(file.getOriginalFilename());
        fileSystem.setFilePath(fileId);
        fileSystem.setBusinessKey(businessKey);
        fileSystem.setFiletag(fileTag);
        if(metadata!=null){
            try{
                Map map = JSON.parseObject(metadata, Map.class);
                fileSystem.setMetadata(map);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        fileSystem.setFileSize(file.getSize());
        fileSystem.setFileType(file.getContentType());
        fileSystemRepository.save(fileSystem);
        return new UploadFileResult(CommonCode.SUCCESS,fileSystem);
    }

    /**
     * 上传到fdfs，返回文件id
     * @param file
     * @return
     */
    public String fdfs_upload(MultipartFile file){
        try {
            initFdfsConfig();
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storeStorage = trackerClient.getStoreStorage(trackerServer);
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storeStorage);
            //上传文件
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            //文件扩展名
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String fileId = storageClient1.upload_appender_file1(bytes, extName, null);
            return fileId;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



}
